// 文件位置: src/main/java/com/pharmacy/SaleManage/controller/SaleRecordController.java
package com.pharmacy.SaleManage.controller;

import com.pharmacy.SaleManage.entity.SaleRecord;
import com.pharmacy.SaleManage.service.SaleRecordService;
import com.pharmacy.UserManage.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sale")
public class SaleRecordController {

    @Autowired
    private SaleRecordService saleRecordService;

    // 获取所有销售记录
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getAllSaleRecords(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return ResponseEntity.status(401).body(response);
        }

        try {
            List<SaleRecord> saleRecords = saleRecordService.getAllSaleRecords();
            response.put("success", true);
            response.put("data", saleRecords);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取销售记录失败");
            return ResponseEntity.status(500).body(response);
        }
    }

    // 按日期范围查询销售记录
    @GetMapping("/records/date-range")
    public ResponseEntity<Map<String, Object>> getSaleRecordsByDateRange(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return ResponseEntity.status(401).body(response);
        }

        try {
            List<SaleRecord> saleRecords = saleRecordService.getSaleRecordsByDateRange(startDate, endDate);
            response.put("success", true);
            response.put("data", saleRecords);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取销售记录失败");
            return ResponseEntity.status(500).body(response);
        }
    }

    // 添加销售记录（需要销售员权限）
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addSaleRecord(@RequestBody SaleRecord saleRecord, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null || !"sales".equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.status(403).body(response);
        }

        // 设置操作员ID
        saleRecord.setOperatorId(currentUser.getId());

        if (saleRecordService.addSaleRecord(saleRecord)) {
            response.put("success", true);
            response.put("message", "销售记录添加成功");
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "库存不足或添加失败");
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取销售统计
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getSalesStatistics(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return ResponseEntity.status(401).body(response);
        }

        try {
            Double totalSales = saleRecordService.getTotalSalesByDateRange(startDate, endDate);
            List<SaleRecord> saleRecords = saleRecordService.getSaleRecordsByDateRange(startDate, endDate);

            response.put("success", true);
            response.put("totalSales", totalSales);
            response.put("recordCount", saleRecords.size());
            response.put("data", saleRecords);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取销售统计失败");
            return ResponseEntity.status(500).body(response);
        }
    }
}